package com.itdct.onflow.core.util

import java.math.RoundingMode

/**
 * 文件大小格式化工具类
 *
 * @author Zhouwx
 * @date 2025/4/17 10:06:00
 * @version 1.0
 */
object FileSizeUtil {
    private const val BYTE = 1L
    private const val KB = BYTE * 1024
    private const val MB = KB * 1024
    private const val GB = MB * 1024
    private const val TB = GB * 1024
    private const val PB = TB * 1024
    private const val EB = PB * 1024

    /**
     * 将字节大小转换为带单位的可读字符串
     *
     * @param fileSize 字节大小，单位为Byte
     * @return 格式化后的带单位字符串，保留两位小数
     */
    fun formatFileSize(fileSize: Long?): String {
        return if (fileSize != null) {
            when {
                fileSize >= EB -> { // Exabyte (EB)
                    val value = fileSize.toDouble() / EB
                    "${value.toBigDecimal().setScale(2, RoundingMode.HALF_UP)}EB"
                }

                fileSize >= PB -> { // Petabyte (PB)
                    val value = fileSize.toDouble() / PB
                    "${value.toBigDecimal().setScale(2, RoundingMode.HALF_UP)}PB"
                }

                fileSize >= TB -> { // Terabyte (TB)
                    val value = fileSize.toDouble() / TB
                    "${value.toBigDecimal().setScale(2, RoundingMode.HALF_UP)}TB"
                }

                fileSize >= GB -> { // Gigabyte (GB)
                    val value = fileSize.toDouble() / GB
                    "${value.toBigDecimal().setScale(2, RoundingMode.HALF_UP)}GB"
                }

                fileSize >= MB -> { // Megabyte (MB)
                    val value = fileSize.toDouble() / MB
                    "${value.toBigDecimal().setScale(2, RoundingMode.HALF_UP)}MB"
                }

                fileSize >= KB -> { // Kilobyte (KB)
                    val value = fileSize.toDouble() / KB
                    "${value.toBigDecimal().setScale(2, RoundingMode.HALF_UP)}KB"
                }

                else -> { // Byte (B)
                    "${fileSize}B"
                }
            }
        } else {
            ""
        }
    }
}